<template>
  <div class="operation-tale">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="70px"
    >
      <el-form-item label="玻璃ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入玻璃ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="玻璃厚度" prop="thick">
        <el-input
          v-model="queryParams.thick"
          placeholder="请输入玻璃厚度"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="clientName">
        <el-input
          v-model="queryParams.clientName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="识别码" prop="optCodeContext">
        <el-input
          v-model="queryParams.optCodeContext"
          placeholder="请输入识别码(XXX,XXX)"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优化包" prop="spareFieldStr5">
        <el-input
          v-model="queryParams.spareFieldStr5"
          placeholder="请输入优化包"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="流程卡" prop="cardcode">
        <el-input
          v-model="queryParams.cardcode"
          placeholder="请输入流程卡"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="格号" prop="plate">
        <el-input
          v-model="queryParams.grid"
          placeholder="请输入格号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="炉号" prop="furMark">
        <el-input
          v-model="queryParams.furMark"
          placeholder="请输入格号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="线号" prop="lineIndex">
        <el-input
          v-model="queryParams.lineIndex"
          placeholder="请输入线号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="玻璃种类" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择">
          <el-option
            v-for="item in Object.keys(typeMap)"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="位置" prop="place">
        <el-select
          v-model="queryParams.place"
          filterable
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="(item,index) in placeData"
            :key="index"
            :label="item.label"
            :value="item.value"
          >
            <span style="float: left">{{ item.label }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{
              item.value
            }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleBatchUpdate(1)"
          v-hasPermi="['assembly:glass:edit']"
          >批量报损</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleBatchUpdate(2)"
          v-hasPermi="['assembly:glass:edit']"
          >批量异常</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-s-operation"
          size="mini"
          @click="handleJobLog"
          v-hasPermi="['production:operation:start']"
          >日志</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['production:operation:import']"
          >导入</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          v-hasPermi="['assembly:glass:edit']"
          @click="handlerPost"
          >位置修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-select
          v-model="priority"
          placeholder="请选择优先级设置类型"
          size="mini"
          @change="updatePriorityValue"
        >
          <el-option label="每天过零点增加优先级" :value="1"> </el-option>
          <el-option label="玻璃停留24小时增加优先级" :value="0"> </el-option>
        </el-select>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="updatePageList"
      ></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="tableSwitch"
      @selection-change="handleSelectionChange"
      :height="total == 0 ? 'calc(100vh - 330px)' : 'calc(100vh - 380px)'"
      :default-sort="{ prop: 'date', order: 'descending' }"
      border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="编号"
        align="center"
        key="id"
        prop="id"
        width="80"
      />
      <el-table-column
        label="优化包批次"
        align="center"
        key="spareFieldStr5"
        fit
        width="180"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.optGlass.spareFieldStr5 || "" }}
        </template>
      </el-table-column>
      <el-table-column
        label="流程卡号"
        align="center"
        key="cardCode"
        fit
        width="100"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          {{ scope.row.optGlass.cardCode || "" }}
        </template>
      </el-table-column>
      <el-table-column
        label="玻璃类型"
        align="center"
        key="type"
        prop="type"
        fit
        min-width="120"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column label="尺寸(宽*高)" align="center" width="120">
        <template slot-scope="scope">
          {{ scope.row.furInWidth + "*" + scope.row.furInHeight }}
        </template>
      </el-table-column>
      <el-table-column
        label="厚度"
        align="center"
        key="thick"
        prop="thick"
        width="60"
      />
      <el-table-column
        label="客户"
        align="center"
        key="clientName"
        prop="clientName"
        fit
        width="150"
        show-overflow-tooltip
      />
      <el-table-column
        label="识别码"
        align="center"
        key="optCodeContext"
        fit
        width="120"
      >
        <template slot-scope="scope">
          <div class="optCodeContext" @click="openInfo(scope.row)">
            {{ scope.row.optCodeContext }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="格号"
        align="center"
        key="grid"
        prop="grid"
        fit
        show-overflow-tooltip
        width="60"
      />
      <el-table-column
        label="炉号"
        align="center"
        key="furMark"
        prop="furMark"
        fit
        show-overflow-tooltip
        width="100"
      />
      <el-table-column
        label="组号"
        align="center"
        key="gridGroup"
        prop="gridGroup"
        fit
        show-overflow-tooltip
        width="60"
      />
      <el-table-column
        label="位置"
        align="center"
        prop="place"
        min-width="200"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.quartz_common_location"
            :value="scope.row.place"
          />
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="80" align="center">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.quartz_glass_state"
            :value="scope.row.state"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="修改时间"
        align="center"
        prop="createTime"
        width="200"
        show-overflow-tooltip
        sortable
      >
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button
            type="text"
            icon="el-icon-edit"
            slot="reference"
            v-hasPermi="['assembly:glass:edit']"
            v-if="showNewLosses"
            @click="openLosses([scope.row])"
            >报损</el-button
          >
          <el-popconfirm
            cancel-button-text="取消"
            confirm-button-text="确定"
            icon="el-icon-info"
            icon-color="red"
            v-if="!showNewLosses"
            @confirm="handleUpdate(scope.row, 1)"
            title="您确定此玻璃报损吗？"
          >
            <el-button
              type="text"
              icon="el-icon-edit"
              slot="reference"
              v-hasPermi="['assembly:glass:edit']"
              >报损</el-button
            >
          </el-popconfirm>
          <el-popconfirm
            cancel-button-text="取消"
            confirm-button-text="确定"
            icon="el-icon-info"
            icon-color="red"
            @confirm="handleUpdate(scope.row, 2)"
            title="您确定此玻璃异常吗？"
          >
            <el-button
              style="padding-left: 10%"
              type="text"
              v-hasPermi="['assembly:glass:edit']"
              icon="el-icon-error"
              slot="reference"
              >异常</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="updatePageList"
      :page-sizes="[20, 50, 70, 100]"
      :page-size="20"
    />
    <!-- 导入工作单OPT -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="uploadFile"
        id="uploadFile"
        accept=""
        :file-list="upload.fileList"
        :action="'#'"
        :on-remove="handleFileRemove"
        :on-change="handleFileChange"
        :auto-upload="false"
        :data="upload.params"
        multiple
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          <em>点击上传文件夹</em>
        </div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>导入文件夹 , 文件夹仅允许放入G代码格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 参数设置 -->
    <el-drawer
      title="参数设置"
      :visible.sync="settingShow"
      size="30%"
      append-to-body
    >
      <div style="height: 100%" v-loading="baseLoad">
        <slot :settingShow="CloseEvent"></slot>
      </div>
    </el-drawer>
    <el-dialog
      title="玻璃位置修改"
      :visible.sync="dialogOpen"
      width="55%"
      append-to-body
    >
      <el-form
        :label-position="labelPosition"
        label-width="120px"
        class="formList"
      >
        <el-form-item label="修改位置至" prop="place">
          <el-select
            v-model="changeObj.place"
            filterable
            placeholder="请选择"
            clearable
            size="mini"
          >
            <el-option
              v-for="item in placeData"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.value
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <el-divider>玻璃列表</el-divider>
      <div class="bottomBody">
        <el-table
          :data="
            tableSwitch
              ? tableSwitch.filter((item) => ids.includes(item.id))
              : []
          "
          height="400px"
          border
        >
          <el-table-column label="编号" align="center" key="id" prop="id" />
          <el-table-column label="尺寸(宽*高)" align="center" width="120">
            <template slot-scope="scope">
              {{ scope.row.furInWidth + "*" + scope.row.furInHeight }}
            </template>
          </el-table-column>
          <el-table-column
            label="厚度"
            align="center"
            key="thick"
            prop="thick"
          />
          <el-table-column
            label="玻璃类型"
            align="center"
            key="type"
            prop="type"
            fit
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="客户"
            align="center"
            key="clientName"
            prop="clientName"
            show-overflow-tooltip
          />
          <el-table-column label="识别码" align="center" key="optCodeContext">
            <template slot-scope="scope">
              <div>
                {{ scope.row.optGlass.barcode }},{{
                  scope.row.optGlass.disturbCode
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="位置"
            align="center"
            prop="place"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.quartz_common_location"
                :value="scope.row.place"
              />
            </template>
          </el-table-column>
          <el-table-column prop="state" label="状态" width="80" align="center">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.quartz_glass_state"
                :value="scope.row.state"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogOpen = false">取 消</el-button>
        <el-button type="primary" @click="handerConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="玻璃信息" :visible.sync="glassInfoSwitch" width="45%">
      <GlassInfo
        v-if="glassInfoSwitch"
        :glass="showGlass"
        @closeDialog="glassInfoSwitch = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import { abnormal } from "@/api/production/quartz";
import {
  updateGlassBatchState,
  updateGlassBatchClear,
} from "@/api/assembly/glass";
import axios from "axios";
import { getToken } from "@/utils/auth";
import { modifyGlassPlace } from "@/api/assembly/glass";
import GlassInfo from "@/views/components/production/glassInfo.vue";
import { mapState } from "vuex";
import { getPriority, updatePriority } from "@/api/production/priority";
export default {
  components: { GlassInfo },
  dicts: [
    "quartz_glass_state",
    "quartz_common_location_search",
    "quartz_common_location",
  ],
  props: {
    tableSwitch: {
      type: Array,
      default: () => [],
    },
    loading: {
      type: Boolean,
      default: true,
    },
    total: {
      type: Number,
      default: 0,
    },
    queryParams: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      priority: 0,
      showGlass: null,
      glassInfoSwitch: false,
      showSearch: true,
      state2: "",
      placeData: [],
      multiple: true,
      ids: [],
      upload: {
        open: false,
        title: null,
        fileList: [],
        params: {},
        isUploading: false,
      },
      settingShow: false,
      baseLoad: true,
      dialogOpen: false,
      labelPosition: "left",
      changeObj: {
        ids: [],
        place: null,
      },
      showNewLosses: sessionStorage.getItem("showNewLosses") || true,
    };
  },
  methods: {
    handlerSwichLosses() {
      this.showNewLosses = !this.showNewLosses;
      sessionStorage.setItem("showNewLosses", this.showNewLosses);
    },
    openLosses(e) {
      this.$openLosses.showDialog(e, this.updatePageList);
    },
    updatePriorityValue() {
      updatePriority({ i: this.priority })
        .then((res) => {
          this.$message.success("修改成功");
        })
        .catch(() => {
          this.$message.error("修改失败");
        });
    },

    getPriorityValue() {
      getPriority().then((res) => {
        this.priority = res.data;
      });
    },

    openInfo(e) {
      this.showGlass = e;
      this.glassInfoSwitch = true;
    },
    handerConfirm() {
      modifyGlassPlace(this.changeObj).then((res) => {
        this.$message.success(res.msg || "操作成功");
        this.dialogOpen = false;
      });
    },
    handlerPost() {
      this.changeObj.ids = this.ids;
      this.dialogOpen = true;
    },
    async handlerBaseParam() {
      this.baseLoad = true;
      let param = [
        {
          name: "笼前",
          id: 0,
        },
      ];
      this.settingShow = true;
      await this.$store.dispatch("getDeviceMap", param);
      this.baseLoad = false;
    },
    CloseEvent() {
      this.settingShow = false;
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.label.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    updatePageList() {
      this.$emit("getList");
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },
    handleBatchUpdate(state) {
      if (sessionStorage.getItem("showNewLosses") == "true" && state == 1) {
        let data = this.tableSwitch.filter((item) =>
          this.ids.includes(item.id)
        );
        this.$openLosses.showDialog(data, () => {
          this.$emit("getList");
        });
      } else {
        this.$prompt("请输入密码", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          inputPattern: /^5563$/,
          inputErrorMessage: "密码错误",
          inputType: "password",
        })
          .then(({ value }) => {
            if (state == 1) {
              updateGlassBatchState(this.ids, state).then((res) => {
                this.$modal.msgSuccess(res.msg);
                this.$emit("getList");
              });
            }
            if (state == 2) {
              updateGlassBatchClear(this.ids, state).then((res) => {
                this.$modal.msgSuccess(res.msg);
                this.$emit("getList");
              });
            }
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "取消输入",
            });
          });
      }
    },
    handleQuery() {
      this.$emit("handleQuery");
    },
    resetQuery() {
      this.$emit("resetQuery");
      this.$store.dispatch("listGlass");
    },
    handleUpdate(row, state) {
      this.$prompt("请输入密码", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^5563$/,
        inputErrorMessage: "密码错误",
        inputType: "password",
      })
        .then(({ value }) => {
          abnormal(row.id, state).then((res) => {
            this.$modal.msgSuccess(res.msg);
            this.updatePageList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
    handleImport() {
      this.upload.title = "导入G代码文件夹";
      this.upload.open = true;
      this.$nextTick(() => {
        this.$refs.uploadFile.clearFiles();
        this.$refs.uploadFile.$children[0].$refs.input.webkitdirectory = true;
      });
    },
    /** 任务日志列表查询 */
    handleJobLog() {
      const jobId = 0;
      this.$router.push({
        path: "/monitor/job-log/index",
        query: { jobId: jobId },
      });
    },
    handleFileChange(file, fileList, name) {
      fileList.forEach((item, index) => {
        if (item.name.split(".")[1] !== "g") {
          fileList.splice(index);
        }
      });
      this.upload.fileList = fileList;
    },
    handleFileRemove(file, fileList, name) {
      this.upload.fileList = fileList;
    },
    // 提交上传文件
    submitFileForm() {
      let folderNames = document
        .getElementsByClassName("el-upload__input")[0]
        .files[0].webkitRelativePath.split("/");
      this.upload.params.folderName = folderNames[folderNames.length - 2];
      if (this.upload.fileList.length === 0) {
        return this.$message.warning("请选取文件后再上传");
      }
      const formData = new FormData();
      this.upload.fileList.forEach((file) => {
        formData.append("file", file.raw);
      });
      formData.append("folderName", this.upload.params.folderName);
      axios({
        url: process.env.VUE_APP_BASE_API + "/dll/opt/uploadingOptG",
        method: "post",
        headers: {
          "Content-Type": "multipart/form-data",
          Authorization: "Bearer " + getToken(),
        },
        data: formData,
      }).then((res) => {
        this.upload.open = false;
        this.$refs.uploadFile.clearFiles();
        this.$alert(
          "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
            res.data.msg +
            "</div>",
          "导入结果",
          { dangerouslyUseHTMLString: true }
        );
      });
    },
  },
  mounted() {
    this.placeData = this.dict.type.quartz_common_location;
    this.getPriorityValue();
  },
  computed: {
    ...mapState({
      totalGlass: (state) => {
        return state.Glass.glass;
      },
    }),
    typeMap() {
      let arr = {};
      this.totalGlass.forEach((item) => {
        if (!arr.hasOwnProperty(item.type)) {
          arr[item.type] = 1;
        } else {
          arr[item.type] += 1;
        }
      });
      return arr;
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.el-divider--horizontal {
  margin: 0 0 15px 0;
}

.el-form-item {
  margin-bottom: 10px;
}

/deep/.el-form-item__content {
  width: 195px;
}

.bottomBody {
  /deep/ .el-table {
    .cell {
      padding: 0 !important;
      font-size: 14px;
    }
  }

  /deep/ .el-dialog__body {
    padding: 10px;
  }
}

.optCodeContext {
  cursor: pointer;
  color: #0082fc;
  

}

.optCodeContext:hover {
  text-decoration: underline;
}

.formList {
  /deep/ .el-form-item__content {
    display: flex;
    flex-direction: row-reverse;
  }
}

/deep/ .el-drawer__header {
  box-shadow: 3px 3px 3xp rgba(0, 0, 0, 15%);
  margin-bottom: 0px;
  padding-bottom: 20px;
  background-color: #f1f3f4;
  font-weight: bold;
  font-size: 17px;
}

/deep/.el-dialog__body {
  padding: 10px 20px 30px 20px !important;
}

.el-table td.el-table__cell div {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.el-icon-upload,
.el-upload__text {
  font-size: 21px;
  position: relative;
  left: 70%;
}

.operation-tale {
  /deep/.el-form-item {
    margin-bottom: 10px;
  }
}

.line-item {
  display: flex;

  .addr {
    max-width: 100px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  .name {
    margin-left: auto;
  }
}
</style>
